package cn.itsource.service.impl;

import cn.itsource.domain.User;
import cn.itsource.mapper.UserMapper;
import cn.itsource.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void transferAccounts(Integer formUser, Integer toUser, Integer amount) {
        //事务就是一组原子性的操作，多个操作，要么同时成功，要么同时失败

        //先扣除formUser的余额
        User form = userMapper.selectById(formUser);
        form.setBalance(form.getBalance() - amount);
        userMapper.update(form);

        int i = 1/0;

        //然后增加toUser的金额
        User to = userMapper.selectById(toUser);
        to.setBalance(to.getBalance() + amount);
        userMapper.update(to);


    }
}
